package com.example.text4;



import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button btnBindService,btnUnbindService,btnGetStatus;
    TextView tvServiceStatus;
    MyService.MyServiceBinder serviceBinder;
    boolean isServiceBind=false;
    ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            serviceBinder= (MyService.MyServiceBinder) service;
            Log.d("MainActivity","Service is connected");
//返回 Service 的 Binder 对象
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("MainActivity","Service is disconnected");
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnBindService=findViewById(R.id.bangding_service);//绑定服务
        btnUnbindService=findViewById(R.id.disbang_service);//解除绑定
        btnGetStatus=findViewById(R.id.get_condition);//获取状态
        tvServiceStatus=findViewById(R.id.zhuangtai);
        btnBindService.setOnClickListener(this);
        btnUnbindService.setOnClickListener(this);
        btnGetStatus.setOnClickListener(this);//以activity为监听器
    }
    @Override
    public void onClick(View v) {
        Intent intent=new Intent();
        intent.setClass(MainActivity.this,MyService.class);
        switch (v.getId()){
            case R.id.bangding_service:
                if(isServiceBind==false)
                {
                    isServiceBind=true;
                    intent.setClass(this,MyService.class);
                    bindService(intent,conn,BIND_AUTO_CREATE);
                }
//如果 service 尚未绑定就绑定，如果已经绑定则忽略
                break;
            case R.id.get_condition:
                if(isServiceBind==true)
                {
                    String s=Integer.toString(serviceBinder.getCount());
                    tvServiceStatus.setText(s);
                }
//如果 service 已经绑定，获取 service 的 count 计数并显示在截面上。
                break;
            case R.id.disbang_service:
//如果 service 已经绑定，则可以解绑，否则忽略
                unbindService(conn);
                intent.setClass(this,MyService.class);
                isServiceBind=false;
                break;
        }
    }
}